﻿using System.IO.Compression;
using System.Text;

namespace Common.Core
{
    public class CompressionHelper
    {
        public static void CreateFromDirectory(string sourceDirectoryName, string destinationArchiveFileName
        )
        {
            ZipFile.CreateFromDirectory(sourceDirectoryName, destinationArchiveFileName
                , CompressionLevel.Fastest, includeBaseDirectory: false, entryNameEncoding: Encoding.UTF8);
        }

        public static byte[] GetZipArchive(Dictionary<string, byte[]> files)
        {
            using (var archiveStream = new MemoryStream())
            {
                using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Create, true, Encoding.UTF8))
                {
                    foreach (var file in files)
                    {
                        if (file.Value is { Length: > 0 })
                        {
                            var zipArchiveEntry = archive.CreateEntry(file.Key, CompressionLevel.Optimal);
                            using (var zipStream = zipArchiveEntry.Open())
                            {
                                zipStream.Write(file.Value, 0, file.Value.Length);
                            }
                        }
                    }
                }
                var archiveFile = archiveStream.ToArray();
                return archiveFile;
            }


        }
        public static async Task<byte[]> GetZipArchiveAsync(Dictionary<string, byte[]> files)
        {
            await using (var archiveStream = new MemoryStream())
            {
                using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Create, true, Encoding.UTF8))
                {
                    foreach (var file in files)
                    {
                        if (file.Value is { Length: > 0 })
                        {
                            var zipArchiveEntry = archive.CreateEntry(file.Key, CompressionLevel.Optimal);
                            await using (var zipStream = zipArchiveEntry.Open())
                            {
                                await zipStream.WriteAsync(file.Value, 0, file.Value.Length);
                            }
                        }
                    }
                }
                var archiveFile = archiveStream.ToArray();
                return archiveFile;
            }


        }
    }
}
